#include <jni.h>
#include <string>

extern "C"
{
#include  "librtmp/rtmp.h"
}

#include <android/log.h>
#include <unistd.h>
#include <pthread.h>

#define TAG "Vic_JNI"
#define LOGE(...) __android_log_print(ANDROID_LOG_INFO,"David",__VA_ARGS__)
JavaVM *gJavaVM = NULL;//全局JavaVM 变量
jobject gJavaObj = NULL;//全局Jobject变量

jmethodID nativeCallback = NULL;//全局的方法ID

static int count = 0;

static void *native_thread_exec(void *arg) {

    LOGE("TAG nativeThreadExec");
    LOGE("TAG The pthread id : %d\n", pthread_self());
    JNIEnv *env;
    //从全局的JavaVM中获取到环境变量
    gJavaVM->AttachCurrentThread(&env, NULL);
    //线程循环
//    for (int i = 0; i < 5; i++) {
//        sleep(2);
//        //跨线程回调Java层函数
//        env->CallVoidMethod(gJavaObj, nativeCallback, count++);
//    }
    gJavaVM->DetachCurrentThread();
    LOGE("thread stoped");
    return ((void *) 0);

}

extern "C"
JNIEXPORT void JNICALL
Java_com_jason_kotlinstudy_MainActivity_nativeInit(JNIEnv *env, jobject object) {
    LOGE("Java_com_xxx_api_thread_NativeThread_nativeInit\n");
    gJavaObj = env->NewGlobalRef(object);//创建全局引用
    jclass clazz = env->GetObjectClass(object);
    nativeCallback = env->GetMethodID(clazz, "onNativeCallBack", "(I)V");

    //操作方式二，调用JNI函数保存JavaVM
    env->GetJavaVM(&gJavaVM);
    pthread_t id;
    //通过pthread库创建线程
    LOGE( "create native thread\n");
    if (pthread_create(&id, NULL, native_thread_exec, NULL) != 0) {
        LOGE("native thread create fail");
        return;
    }
    for (int i = 0; i < 5; i++) {
        usleep(20);
        //跨线程回调Java层函数
        env->CallVoidMethod(gJavaObj, nativeCallback, count++);
    }

    LOGE( "native thread creat success");

}


//SO动态库加载一定会在该流程
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    LOGE( "JNI_OnLoad\n");
    JNIEnv *env = NULL;
    //获取JNI_VERSION版本
    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
        LOGE("checkversion error\n");
        return -1;
    }
    //操作方式一，通过SO加载时保存全局JavaVM
    //gJavaVM = vm;

    //返回jni 的版本
    return JNI_VERSION_1_6;
}

